package com.bkitmobile.kesu.appengine.web.client.SupportPopup;

import java.util.Date;
import java.util.HashMap;

import com.bkitmobile.kesu.appengine.web.client.GreetingService;
import com.bkitmobile.kesu.appengine.web.client.GreetingServiceAsync;
import com.bkitmobile.kesu.appengine.web.client.SupportPopup.LocationInfoPopup.addBtnClick;
import com.bkitmobile.kesu.appengine.web.client.entity.PlaceClient;
import com.bkitmobile.kesu.appengine.web.client.entity.UserInfo;
import com.bkitmobile.kesu.appengine.web.client.utility.LocationInfoPopupConstant;
import com.bkitmobile.kesu.appengine.web.client.utility.LoginPopupConstant;
import com.bkitmobile.kesu.appengine.web.client.utility.RegisterPopupConstant;
import com.google.gwt.core.client.GWT;
import com.google.gwt.event.logical.shared.ValueChangeEvent;
import com.google.gwt.event.logical.shared.ValueChangeHandler;
import com.google.gwt.user.client.Window;
import com.google.gwt.user.client.rpc.AsyncCallback;
import com.google.gwt.user.client.ui.Button;
import com.google.gwt.user.client.ui.ClickListener;
import com.google.gwt.user.client.ui.DialogBox;
import com.google.gwt.user.client.ui.FormHandler;
import com.google.gwt.user.client.ui.FormPanel;
import com.google.gwt.user.client.ui.FormSubmitCompleteEvent;
import com.google.gwt.user.client.ui.FormSubmitEvent;
import com.google.gwt.user.client.ui.HorizontalPanel;
import com.google.gwt.user.client.ui.Label;
import com.google.gwt.user.client.ui.ListBox;
import com.google.gwt.user.client.ui.PasswordTextBox;
import com.google.gwt.user.client.ui.RadioButton;
import com.google.gwt.user.client.ui.RichTextArea;
import com.google.gwt.user.client.ui.RootPanel;
import com.google.gwt.user.client.ui.TextBox;
import com.google.gwt.user.client.ui.ToggleButton;
import com.google.gwt.user.client.ui.VerticalPanel;
import com.google.gwt.user.client.ui.Widget;
import com.google.gwt.user.datepicker.client.DatePicker;

public class ConfigureAccountPopup extends DialogBox {
	private HashMap<String, Widget> InputParam = 
		new HashMap<String, Widget> ();
	private final GreetingServiceAsync greetingService = GWT
		.create(GreetingService.class);
	private final FormPanel form = new FormPanel();
	
	///// Cac field bat buoc: username, pid, sex, email
	/// tra ve true neu 1 trong cac field bat buoc do trong
	private final boolean hasNullValue() {
		// TODO Auto-generated method stub
		TextBox username = (TextBox) this.InputParam.get(RegisterPopupConstant.userName);
		//PasswordTextBox pid = (PasswordTextBox) this.InputParam.get(RegisterPopupConstant.pid);
		TextBox email = (TextBox) this.InputParam.get(RegisterPopupConstant.email);
		if (username.getText().isEmpty() || email.getText().isEmpty())
			return true;
		else
			return false;
	}
	
	private boolean checkDate (int date, int month, int year)
	{
		switch (month)
		{
		case 1:
		case 3:
		case 5:
		case 7:
		case 8:
		case 10:
		case 12:
			if (date <= 31 && date >0)
				return true;
			else 
				return false;
		case 4:
		case 6:
		case 9:
		case 11:
			if (date <= 30 && date >0)
				return true;
			else
				return false;
		case 2:
			if ((year%4==0 && year%100!=0) || year%400 == 0)
			{
				if (date <=28 && date >0)
					return true;
				else
					return false;
			}
			else
			{
				if (date <=27 && date >0)
					return true;
				else
					return false;
			}
		}
		return false;
	}
	
	private String getBdString (int date, int month, String year)
	{
		//DatePicker tmp = new DatePicker();
		if (checkDate(date,month,Integer.parseInt(year)))
			return Integer.toString(date) + "/" + Integer.toString(month)+"/"+year;
		else 
			return "";
	}
	
	private final boolean isMale()
	{
		String title = RegisterPopupConstant.sex + RegisterPopupConstant.male;
		RadioButton free = (RadioButton) InputParam.get(title);
		return free.isChecked();
	}
	
	private final boolean isFree()
	{
		String title = RegisterPopupConstant.usrKind + RegisterPopupConstant.free;
		RadioButton male = (RadioButton) InputParam.get(title);
		return male.isChecked();
	}
	
	private final UserInfo getInfo()
	{
		UserInfo usr = new UserInfo();
		TextBox usr_name = (TextBox) InputParam.get(RegisterPopupConstant.userName);
		usr.setUserName(usr_name.getText());
		//PasswordTextBox pid = (PasswordTextBox) InputParam.get(RegisterPopupConstant.pid);
		//PasswordTextBox confirm_pid = (PasswordTextBox) InputParam.get(RegisterPopupConstant.authen_pid);
		//if (!pid.getText().equals(confirm_pid.getText()))
		//{
		//	Window.alert("Ban nhap mat khau khong dung");
		//	return null;
		//}
		
		TextBox email = (TextBox) InputParam.get(RegisterPopupConstant.email);
		String email_str = email.getText();
		if (email_str.split("@").length<2)
		{
			Window.alert("Ban nhap email khong dung");
			return null;
		}
		usr.setEmail(email_str);
//		usr.setPid(pid.getText());
		TextBox fName = (TextBox) InputParam.get(RegisterPopupConstant.fName);
		usr.setfName(fName.getText());
		TextBox lName = (TextBox) InputParam.get(RegisterPopupConstant.lName);
		usr.setlName(lName.getText());
		
		ListBox bday_date = (ListBox) InputParam.get(RegisterPopupConstant.bday+"date");
		ListBox bday_month = (ListBox) InputParam.get(RegisterPopupConstant.bday+"month");
		ListBox bday_year = (ListBox) InputParam.get(RegisterPopupConstant.bday+"year");
		//usr.setBday(bday.getText());
		String bday = this.getBdString(bday_date.getSelectedIndex()+1,bday_month.getSelectedIndex()+1,
				bday_year.getItemText(bday_year.getSelectedIndex()));
		if (bday.equals(""))
		{
			Window.alert("Ban da dien ngay sinh sai");
			return null;
		}
		
		usr.setBday(bday);
		//usr.setSex(this.isMale());
		//usr.setPremium(!this.isFree());
		
		return usr;
	}
	
	private HorizontalPanel createTextPanel (String title)
	{
		HorizontalPanel create = new HorizontalPanel();
		Label name = new Label();
		name.setText(title);
		name.setPixelSize(150, 20);
		create.add(name);
		
		TextBox input = new TextBox();
		input.setPixelSize(300, 20);
		create.add(input);
		InputParam.put(title, input);
		
		return create;
	}
	
	private HorizontalPanel createLabelPanel (String title, String detail)
	{
		HorizontalPanel create = new HorizontalPanel();
		Label name = new Label();
		name.setText(title);
		name.setPixelSize(150, 20);
		create.add(name);
		
		Label input = new Label();
		input.setPixelSize(300, 20);
		input.setText(detail);
		create.add(input);
		//InputParam.put(title, input);
		
		return create;
	}
	
	private HorizontalPanel createPasswordPanel (String title)
	{
		HorizontalPanel create = new HorizontalPanel();
		Label name = new Label();
		name.setText(title);
		name.setPixelSize(150, 20);
		create.add(name);
		
		PasswordTextBox input = new PasswordTextBox();
		input.setPixelSize(300, 20);
		create.add(input);
		InputParam.put(title, input);
		
		return create;
	}
	
	
	private HorizontalPanel createDatePanel (String title)
	{
		HorizontalPanel create = new HorizontalPanel();
		Label name = new Label();
		name.setText(title);
		name.setPixelSize(150, 20);
		create.add(name);
		int month_size = 125;
		int date_size = 50;
		int year_size = 60;
		
		Label tmp;
		ListBox date_info = new ListBox();
		create.add(date_info);
		date_info.setPixelSize(date_size, 20);
		for (int i = 1;i<=31;i++)
			date_info.addItem(Integer.toString(i));
		InputParam.put(title+"date", date_info);
		tmp = new Label();
		tmp.setPixelSize(15, 20);
		create.add(tmp);
		
		/////create month input
		ListBox month_info = new ListBox();
		create.add(month_info);
		month_info.setPixelSize(month_size, 20);
		for (String i:RegisterPopupConstant.month_const)
			month_info.addItem(i);
		InputParam.put(title+"month", month_info);
		tmp = new Label();
		tmp.setPixelSize(15, 20);
		create.add(tmp);
		
		
		///// create year input
		ListBox year_info = new ListBox();
		create.add(year_info);
		year_info.setPixelSize(year_size, 20);
		for (int i = 1900;i<2010;i++)
			year_info.addItem(Integer.toString(i));
		InputParam.put(title+"year", year_info);
		
		return create;
	}
	
	private HorizontalPanel createDatePanel (String title, String date)
	{
		HorizontalPanel create = new HorizontalPanel();
		Label name = new Label();
		name.setText(title);
		name.setPixelSize(150, 20);
		create.add(name);
		int month_size = 125;
		int date_size = 50;
		int year_size = 60;
		
		Label tmp;
		ListBox date_info = new ListBox();
		create.add(date_info);
		date_info.setPixelSize(date_size, 20);
		for (int i = 1;i<=31;i++)
			date_info.addItem(Integer.toString(i));
		InputParam.put(title+"date", date_info);
		tmp = new Label();
		tmp.setPixelSize(15, 20);
		create.add(tmp);
		
		/////create month input
		ListBox month_info = new ListBox();
		create.add(month_info);
		month_info.setPixelSize(month_size, 20);
		for (String i:RegisterPopupConstant.month_const)
			month_info.addItem(i);
		InputParam.put(title+"month", month_info);
		tmp = new Label();
		tmp.setPixelSize(15, 20);
		create.add(tmp);
		
		
		///// create year input
		ListBox year_info = new ListBox();
		create.add(year_info);
		year_info.setPixelSize(year_size, 20);
		for (int i = 1900;i<2010;i++)
			year_info.addItem(Integer.toString(i));
		InputParam.put(title+"year", year_info);
		
		String[] bday = date.split("/");
		date_info.setSelectedIndex(Integer.parseInt(bday[0])-1);
		month_info.setSelectedIndex(Integer.parseInt(bday[1])-1);
		year_info.setSelectedIndex(Integer.parseInt(bday[2])-1900);
		
		return create;
	}
	
	private HorizontalPanel createChoicePanel (String title,String[] choice)
	{
		HorizontalPanel create = new HorizontalPanel();
		Label name = new Label();
		name.setText(title);
		name.setPixelSize(150, 20);
		create.add(name);
		
		for (int i = 0; i<choice.length;i++)
		{
			RadioButton input = new RadioButton(title,choice[i]);
			input.setPixelSize(300/choice.length, 20);
			create.add(input);
			input.setChecked(true);
			InputParam.put(title + choice[i], input);
		}
		
		return create;
	}
	
	private void hidePanel()
	{
		this.hide();
	}
	
	private void hideAllWidget()
	{
		this.clear();
	}
	
	private void inputInfo (final UserInfo info)
	{
		
		//create the form panel, set its action and method
		form.setHeight("300px");
		form.setMethod(FormPanel.METHOD_GET);
		//set the main widget for the panel to a vertical panel
		VerticalPanel panel = new VerticalPanel();
		panel.setSpacing(4);
		panel.add(createLabelPanel("T\u00ean t\u00e0i kho\u1ea3n", info.getUserName()));
		panel.add(createLabelPanel("H\u1ecd", info.getfName()));
		panel.add(createLabelPanel("T\u00ean", info.getlName()));
		String sex;
		if (info.isSex())
			sex = "Nam";
		else
			sex = "N\u1eef";
		panel.add(createLabelPanel("Gi\u1edbi t\u00ednh", sex ));
		panel.add(createLabelPanel("Ng\u00e0y sinh", info.getBday()));
		panel.add(createLabelPanel("Email", info.getEmail()));
		panel.add(createLabelPanel("S\u1ed1 \u0111\u1ecba \u0111i\u1ec3m c\u00f2n l\u1ea1i",
				Integer.toString(info.getPlaceLeft())));
		
		Button add_btn = new Button();
		add_btn.setText("Thay \u0111\u1ed5i");
		Button cancel_btn = new Button();
		cancel_btn.setText("Tho\u00e1t");
		Button change_pid_btn = new Button();
		change_pid_btn.setText("Thay \u0111\u1ed5i m\u1eadt kh\u1ea9u");
		
		/////// Xu ly su kien add thanh cong
		cancel_btn.addClickListener(new ClickListener() {
			
			@Override
			public void onClick(Widget sender) {
				// TODO Auto-generated method stub
				hidePanel();
			}
		});
		
		add_btn.addClickListener(new ClickListener() {
			
			@Override
			public void onClick(Widget sender) {
				// TODO Auto-generated method stub
				hideAllWidget();
				createConfigureField(info);
				
			}
		});
		
		change_pid_btn.addClickListener(new ClickListener() {
			
			@Override
			public void onClick(Widget sender) {
				// TODO Auto-generated method stub
				hideAllWidget();
				createPidChangeField(info);
			}
		});
		
		
		//////// Add vao panel
		HorizontalPanel button = new HorizontalPanel();
		button.add(add_btn);
		button.add(cancel_btn);
		button.add(change_pid_btn);
		button.setSpacing(5);
		panel.add(button);
		form.setWidget(panel);
		////// khong dung add vi glass panel se che mat popup
		this.setWidget(form);
		this.setPopupPosition(425, 146);

		
	}
	
	private void createConfigureField (UserInfo info)
	{
		//set the main widget for the panel to a vertical panel
		VerticalPanel panel = new VerticalPanel();
		panel.setSpacing(4);
		panel.add(createTextPanel(RegisterPopupConstant.userName));
		TextBox usrName = (TextBox) InputParam.get(RegisterPopupConstant.userName);
		usrName.setText(info.getUserName());
		usrName.setEnabled(false);
		
//		panel.add(createPasswordPanel(RegisterPopupConstant.pid));
//		PasswordTextBox pid = (PasswordTextBox) InputParam.get(RegisterPopupConstant.pid);
//		pid.setValue(info.getPid());
		
//		panel.add(createPasswordPanel(RegisterPopupConstant.authen_pid));
//		PasswordTextBox authen_pid = (PasswordTextBox) InputParam.get(RegisterPopupConstant.authen_pid);
//		authen_pid.setText(info.getPid());
		
		panel.add(createTextPanel(RegisterPopupConstant.fName));
		TextBox fName = (TextBox) InputParam.get(RegisterPopupConstant.fName);
		fName.setText(info.getfName());
		
		panel.add(createTextPanel(RegisterPopupConstant.lName));
		TextBox lName = (TextBox) InputParam.get(RegisterPopupConstant.lName);
		lName.setText(info.getlName());
		
		panel.add(createDatePanel(RegisterPopupConstant.bday,info.getBday()));
		
		panel.add(createTextPanel(RegisterPopupConstant.email));
		TextBox email = (TextBox) InputParam.get(RegisterPopupConstant.email);
		email.setText(info.getEmail());
		
		//String [] sex = RegisterPopupConstant.sexes;
		//panel.add(createChoicePanel(RegisterPopupConstant.sex, sex ));
		
		//String [] specific_usr = RegisterPopupConstant.specific_usr;
		//panel.add(createChoicePanel(RegisterPopupConstant.usrKind, specific_usr));
		
		Button cancel_btn = new Button();
		cancel_btn.addClickListener(new ClickListener() {
			
			@Override
			public void onClick(Widget sender) {
				// TODO Auto-generated method stub
				hide();
			}
		});
		cancel_btn.setText("Tho\u00e1t");
		Button submit_btn = new Button();
		submit_btn.setText("Thay \u0111\u1ed5i");
		submit_btn.addClickListener(new ClickListener() {
			
			@Override
			public void onClick(Widget sender) {
				// TODO Auto-generated method stub
				if (hasNullValue())
				{
					Window.alert("B\u1ea1n ph\u1ea3i \u0111i\u1ec1n " +
							"to\u00e0n b\u1ed9 c\u00e1c \u00f4 tr\u1ed1ng");
				}
				else
				{
					UserInfo input = getInfo();
					if (input!=null)
					{
						greetingService.doUpdate(input, new AsyncCallback<String>() {

							@Override
							public void onFailure(Throwable caught) {
								// TODO Auto-generated method stub	
							}

							@Override
							public void onSuccess(String result) {
								// TODO Auto-generated method stub	
							}
						});
						Window.Location.reload();
					}
				}
				
			}
		});
		
		//Add 2 button into form
		HorizontalPanel horizon = new HorizontalPanel();
		horizon.setSpacing(5);
		horizon.add(submit_btn);
		horizon.add(cancel_btn);
		
		panel.add(horizon);
		
		form.setWidget(panel);
		
		this.setWidget(form);
		this.setText("Th\u00f4ng tin thay \u0111\u1ed5i");
		// Enable animation.
		setAnimationEnabled(true);

		  
		// Enable glass background.
		setGlassEnabled(true);
		this.setPopupPosition(400, 50);
	}
	
	private void createPidChangeField (final UserInfo info)
	{
		//set the main widget for the panel to a vertical panel
		VerticalPanel panel = new VerticalPanel();
		panel.setSpacing(4);
		panel.add(createTextPanel(RegisterPopupConstant.userName));
		final TextBox usrName = (TextBox) InputParam.get(RegisterPopupConstant.userName);
		usrName.setText(info.getUserName());
		usrName.setEnabled(false);
		
		panel.add(createPasswordPanel(RegisterPopupConstant.pid));
		final PasswordTextBox pid = (PasswordTextBox) InputParam.get(RegisterPopupConstant.pid);
		
		panel.add(createPasswordPanel(RegisterPopupConstant.authen_pid));
		final PasswordTextBox authen_pid = (PasswordTextBox) InputParam.get(RegisterPopupConstant.authen_pid);
		

		
		Button cancel_btn = new Button();
		cancel_btn.addClickListener(new ClickListener() {
			
			@Override
			public void onClick(Widget sender) {
				// TODO Auto-generated method stub
				hide();
			}
		});
		cancel_btn.setText("Tho\u00e1t");
		Button submit_btn = new Button();
		submit_btn.setText("Thay \u0111\u1ed5i");
		submit_btn.addClickListener(new ClickListener() {
			
			@Override
			public void onClick(Widget sender) {
				// TODO Auto-generated method stub
				boolean isAvailable = true;
				String pid_txt = pid.getValue();
				String pid_authen_txt = authen_pid.getValue();
				
				if (pid_txt.isEmpty() || pid_authen_txt.isEmpty())
				{
					Window.alert("B\u1ea1n ph\u1ea3i \u0111i\u1ec1n th\u00f4ng " +
							"tin v\u00e0o c\u00e1c \u00f4 tr\u00ean");
					isAvailable = false;	
				}
				else if (!pid_txt.equals(pid_authen_txt))
				{
					Window.alert("B\u1ea1n nh\u1eadp m\u1eadt kh\u1ea9u kh\u00f4ng " +
							"\u0111\u00fang. Xin vui l\u00f2ng nh\u1eadp l\u1ea1i");
					isAvailable = false;	
				}
				else 
				{
					info.setPid(pid_txt);
				}
				
				if (isAvailable)
				{
					greetingService.doUpdate(info, new AsyncCallback<String>() {
							@Override
							public void onFailure(Throwable caught) {
								// TODO Auto-generated method stub	
							}
							@Override
							public void onSuccess(String result) {
								// TODO Auto-generated method stub	
							}
					});
					Window.Location.reload();
				}
			}
		});
		
		//Add 2 button into form
		HorizontalPanel horizon = new HorizontalPanel();
		horizon.setSpacing(5);
		horizon.add(submit_btn);
		horizon.add(cancel_btn);
		
		panel.add(horizon);
		
		form.setWidget(panel);
		
		this.setWidget(form);
		this.setText("Th\u00f4ng tin thay \u0111\u1ed5i");
		// Enable animation.
		setAnimationEnabled(true);

		  
		// Enable glass background.
		setGlassEnabled(true);
		this.setPopupPosition(400, 50);
	}
	
	@SuppressWarnings("deprecation")
	public ConfigureAccountPopup()
	{
		this.setText("Th\u00f4ng tin ng\u01b0\u1eddi d\u00f9ng");
		// Enable animation.
		setAnimationEnabled(true);
		// Enable glass background.
		setGlassEnabled(true);
		greetingService.checkLogin("", new AsyncCallback<String>() {
			
			@Override
			public void onSuccess(String result_fr) {
				// TODO Auto-generated method stub
				if (!result_fr.equals(""))
				{
					greetingService.getUsrInfo(result_fr, new AsyncCallback<UserInfo>() {

						@Override
						public void onFailure(Throwable caught) {
							// TODO Auto-generated method stub
							
						}

						@Override
						public void onSuccess(UserInfo result) {
							// TODO Auto-generated method stub
							if (result == null)
							{
								Window.alert("\u0110\u00e3 c\u00f3 l\u1ed7i x\u1ea3y ra. Xin b\u1ea1n vui l\u00f2ng tho\u00e1t" +
										" ra v\u00e0 \u0111\u0103ng nh\u1eadp l\u1ea1i");
								hidePanel();
							}
							else
								inputInfo(result);
						}
					});
				}
				else
				{
					Window.alert("\u0110\u00e3 c\u00f3 l\u1ed7i x\u1ea3y ra. Xin b\u1ea1n vui l\u00f2ng tho\u00e1t " +
							"ra v\u00e0 \u0111\u0103ng nh\u1eadp l\u1ea1i");
					hidePanel();
				}
			}
			
			@Override
			public void onFailure(Throwable caught) {
				// TODO Auto-generated method stub
				
			}
		});
	}

}
